// Jenkinsfile (Declarative Pipeline)
pipeline {
    agent { 
        node { 
            label "master"
        }
    }
    parameters {
        choice(name: 'fresh', choices: ['false', 'true'], description: 'fresh if ture will force run')
    }
    environment {
        USER_NAME = "Sylvia"
        CURRENT_USER_INFO_JSON = "${env.USER_NAME}_info.json"
        LAST_USER_INFO_JSON = "last_${env.USER_NAME}_info.json"
    }
    triggers{ cron('H 8 * * *') }
    options {
        buildDiscarder(logRotator(numToKeepStr: '100'))
        disableConcurrentBuilds()
        timeout(time: 10, unit: 'MINUTES')
        timestamps()
    }
    stages {
        stage("Detect Changes") {
            steps {
                script {
                    def get_user_info = 1
                    retry(3) {
                        get_user_info = sh(script:"""
                            sudo -u www-data php ${OCC} user:info --output=json ${USER_NAME} > ${env.CURRENT_USER_INFO_JSON}
                        """, returnStatus: true, label: "Get User Info")
                    }
                    def user_info = ""
                    def last_user_info = ""
                    def is_changed = false
                    if ( get_user_info == 0 ) {
                        user_info = readJSON file: "${env.CURRENT_USER_INFO_JSON}"
                        if ( fileExists(file: "${env.LAST_USER_INFO_JSON}") ) {
                            last_user_info = readJSON file: "${env.LAST_USER_INFO_JSON}"
                            println user_info["last_seen"]
                            println last_user_info["last_seen"]
                            if ( user_info["last_seen"] != last_user_info["last_seen"] ) {
                                is_changed = true
                            }
                        } else {
                            is_changed = true
                        }
                        sh """mv ./${env.CURRENT_USER_INFO_JSON} ./${env.LAST_USER_INFO_JSON}"""
                    }
                    env.is_changed = is_changed
                    env.file_loc = user_info["user_directory"].toString()

                    echo env.is_changed
                    if ( env.is_changed == "true" || params.fresh == "true" ) {
                        echo "Trigger to Update"
                    } else {
                        throw new Exception("No Need Update")
                    }
                }
            }
        }
        stage("Stash Local Painter") {
            environment {
                STASH_PATH = "Local"
                RELEATIVE_PATH = "/files/seraph/"
            }
            steps {
                script {
                    def pic_type = ["*.jpg", "*.png"]
                    dir(STASH_PATH) {
                        sh(script:"""rm -rf *""", label: "delete all file")
                        dir("${env.file_loc}/${RELEATIVE_PATH}") {
                            for ( type in pic_type ) {
                                if ( findFiles(glob: "${type}") ) {
                                    sh(script:"""cp ${type} ${WORKSPACE}/${STASH_PATH}""", label: "Copy ref file")
                                }
                            }
                        }
                        stash(name: "PAINTER", includes: "**")
                    }

                }
            }
        }
        stage("Make ReadMe File") {
            environment {
                GIT_USER = credentials('738c91c7-b569-4061-8701-213ebf23714b')
                GIT_BRANCH = "dev"
                GIT_URL = 'https://gitee.com/code-one/seraph.git'
                PIC_BIG_FOLD = "picture_album"
                PIC_SMALL_FOLD = "snapshot"
            }
            steps {
                script {
                    dir("Remote") {
                        git branch: env.GIT_BRANCH, credentialsId: env.GIT_USER, url: env.GIT_URL
                        dir(PIC_BIG_FOLD) {
                            deleteDir()
                            dir(PIC_SMALL_FOLD) {
                                deleteDir()
                            }
                            unstash(name: "PAINTER")
                            pic_list = findFiles(glob: "*")
                            for (p in pic_list) {
                                sh(script: """
                                    ${PYTHON} ./../tools/resize_pic.py -i "${p}" -o "${env.PIC_SMALL_FOLD}/${p}"
                                """, returnStatus: true, label: "resize album")
                            }
                        }
                        sh(script: """
                            ${PYTHON} tools/generate_readme.py -i ${env.PIC_BIG_FOLD}/${env.PIC_SMALL_FOLD} -o README.md
                            cat README.md
                        """, returnStatus: true, label: "Generate readme file")

                        
                    }
                }
            }
        }
        stage("Push To Gitee") {
            environment {
                GIT_BRANCH = "dev"
            }
            steps {
                script {
                    dir("Remote") {
                        def current_time = new Date().format('yyyyMMddHHmmss') + "_${env.BUILD_ID}"
                        def git_return_code = sh(script: """
                            git add *
                            git commit -m "${current_time} - auto"
                        """, returnStatus: true, label: "new commit")
                        if ( git_return_code == 0 ) {
                            sh(script: """
                                git push origin ${GIT_BRANCH}
                            """)
                        } else {
                            echo "No file need to push"
                        }
                    }
                }
            }
        }
    }
    post {
        success {
            emailext body: "Sync to Seraph Page Success<hr>Git Page: https://gitee.com/code-one/seraph/blob/dev/README.md",
                subject: """${env.JOB_NAME} - Build ${env.BUILD_NUMBER}""",
                to: "271243712@qq.com, 1321337879@qq.com"
        }
        failure {
            echo "fail"
        }
        always {
            echo "always"
        }
    }
}
